package com.gouda.core.dao;

import com.google.common.collect.Maps;
import com.gouda.core.entity.UserServiceIntroduceEntity;
import com.gouda.core.utils.CacheKey;
import com.hephaestus.cache.CacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.amethyst.atlas.db.MagicDao;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * Created by souu on 15/12/6.
 */
@Slf4j
@Repository
public class UserServiceIntroduceDao extends MagicDao {

    private static final String BASE_SQL_ID = "select id from user_service_introduce";

    public UserServiceIntroduceEntity getUserServiceIntroduce(long serviceTypeId, long uid) {
        if (uid <= 0 || serviceTypeId <= 0) {
            return null;
        }

        Long id = (Long) CacheUtil.getInstance().get(CacheKey.getUserServiceIntroduce(uid, serviceTypeId));
        if (id == null || id <= 0) {
            String sql = BASE_SQL_ID + " where uid =:uid and st_id = :stId";
            Map<String, Object> param = Maps.newHashMap();
            param.put("uid", uid);
            param.put("stId", serviceTypeId);
            List<Long> ids = this.listColumns(UserServiceIntroduceEntity.class, sql, param, Long.class);
            if (CollectionUtils.isEmpty(ids)) {
                return null;
            }
            id = ids.get(0);
            try {
                CacheUtil.getInstance().add(CacheKey.getUserServiceIntroduce(uid, serviceTypeId), id);
            } catch (InterruptedException e) {
                log.error("getUserServiceIntroduce cache error:{}", e.getMessage());
            }
        }

        return this.unique(UserServiceIntroduceEntity.class, id);
    }
}
